<template>
  <view class="phxx-item-detail">
    <view class="content-box">
      <view class="bottom block-back">
        <view class="uni-form-item">
          <view class="title"><span style="color: red">*</span>供应商：</view>
          <view class="uni-select-box">
            <picker mode="selector" range-key="customerName" :disabled="inputObj.id" :range="supplierList"
              :value="supplierIndex" @change="changeSupplier">
              <view v-if="inputObj.supplier.customerName" class="uni-input">{{
                inputObj.supplier.customerName || ''
                }}</view>
              <view v-else class="placeholder">请选择</view>
            </picker>
            <uni-icons v-if="!inputObj.id" type="forward" size="20"></uni-icons>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color: red">*</span>产品类别：</view>
          <view class="uni-select-box">
            <picker mode="selector" range-key="value" :range="coalTypeList" :value="coalTypeIndex"
              @change="changeCoalType">
              <view v-if="inputObj.productType.value" class="uni-input">{{
                inputObj.productType.value || ''
                }}</view>
              <view v-else class="placeholder">请选择</view>
            </picker>
            <uni-icons type="forward" size="20"></uni-icons>
          </view>
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color: red">*</span>产品名称：</view>
          <input :maxlength="20" class="uni-input" placeholder="请输入" v-model="inputObj.proName" />
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color: red">*</span>产品价格：</view>
          <input type="digit" :maxlength="9" class="uni-input" placeholder="请输入" v-model="inputObj.proPrice" />
          <text>元/吨</text>
        </view>
        <view class="uni-form-item">
          <view class="title"><span style="color: red">*</span>发热量：</view>
          <input type="digit" :maxlength="9" class="uni-input" placeholder="请输入" v-model="inputObj.calorificValue" />
          <text>大卡</text>
        </view>
        <view class="uni-form-item">
          <view class="title">灰分：</view>
          <input type="digit" :maxlength="6" class="uni-input" placeholder="请输入" v-model="inputObj.ashContent" />
          <text>%</text>
        </view>
        <view class="uni-form-item">
          <view class="title">硫分：</view>
          <input type="digit" :maxlength="6" class="uni-input" placeholder="请输入" v-model="inputObj.sulfurContent" />
          <text>%</text>
        </view>
        <view class="uni-form-item">
          <view class="title">水分：</view>
          <input type="digit" :maxlength="6" class="uni-input" placeholder="请输入" v-model="inputObj.hydration" />
          <text>%</text>
        </view>
        <view class="uni-form-item">
          <view class="title">挥发分：</view>
          <input type="digit" :maxlength="6" class="uni-input" placeholder="请输入" v-model="inputObj.volatileMatter" />
          <text>%</text>
        </view>
        <view class="uni-form-item" style="height: 220rpx; justify-content: flex-start">
          <view class="title" style="white-space: nowrap">化验单：</view>
          <view class="upload-box" @click="selectPicture">
            <view class="img-box">
              <image class="cover-img" :src="inputObj.assayReport.url || imagesDefaultPath" mode="aspectFill"></image>
              <image class="camera-imgs" :src="imagesCamera" mode="aspectFill"></image>
              <view class="img-text text-color-common-self">{{
                inputObj.assayReport.url ? '重新上传' : '点击上传化验单'
                }}</view>
            </view>
          </view>
        </view>
        <view class="btns">
          <button type="primary" @click="handleSave">提交</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { toast } from '@/utils/common';
  import { getDriverId } from '@/utils/auth';
  import { getAccessToken, getTenantId } from '@/utils/auth';
  import {
    createProduct,
    updateProduct,
    getProductById,
    getSimpleList,
    getProductByEnterId,
    reportProduct
  } from '@/api/product';
  import config from '@/config';
  export default {
    data() {
      return {
        coalTypeList: [],
        supplierList: [],
        supplierIndex: 0,
        coalTypeIndex: 0,
        inputObj: {
          id: undefined,
          supplier: null,
          productType: null,
          proName: '',
          proPrice: undefined,
          calorificValue: undefined,
          ashContent: undefined,
          sulfurContent: undefined,
          hydration: undefined,
          volatileMatter: undefined,
          assayReport: null
        }
      };
    },
    computed: {
      ...mapGetters(['curTypeColor']),
      imagesDefaultPath() {
        return config.baseImgUrl + '/camera-bg.png';
      },
      imagesCamera() {
        if (this.curTypeColor === '#409EFE') {
          return config.baseImgUrl + '/camera.png';
        }
        if (this.curTypeColor === '#D22C2C') {
          return config.baseImgUrl + '/camera1.png';
        }
      }
    },
    onReady() {
      uni.setNavigationBarTitle({
        title: uni.getStorageSync('title')
      });
    },
    async onLoad(option) {
      await this.getSimpleList();
      await this.getProductByEnterId();
      this.inputObj.id = option?.id;
      if (this.inputObj.id) {
        this.getProductById();
      }
    },

    methods: {
      changeSupplier(value) {
        const index = value.detail.value;
        this.inputObj.supplier = this.supplierList[index];
      },
      changeCoalType(value) {
        const index = value.detail.value;
        this.inputObj.productType = this.coalTypeList[index];
      },

      async getSimpleList() {
        const res = await getSimpleList();
        if (res?.code === 0) {
          this.supplierList = res?.data || [];
        } else {
          toast('请求失败');
        }
      },

      async getProductByEnterId() {
        const res = await getProductByEnterId();
        if (res?.code === 0) {
          this.coalTypeList = res?.data || [];
        } else {
          toast('请求失败');
        }
      },

      async getProductById() {
        try {
          const data = { id: this.inputObj.id };
          const res = await getProductById(data);
          if (res.code === 0) {
            this.handleProductData(res.data);
          }
        } catch {
          return false;
        }
      },

      handleProductData(result) {
        if (!result) {
          return;
        }
        Object.keys(this.inputObj).forEach((key) => {
          this.inputObj[key] = result[key];
        });
        this.inputObj.supplier = this.supplierList.find(
          (e) => e.id === result.supplierId
        );
        this.inputObj.productType = this.coalTypeList.find(
          (e) => e.code === result.productType
        );
        this.supplierIndex = this.supplierList.findIndex(
          (e) => e.id === result.supplierId
        );
        this.coalTypeIndex = this.coalTypeList.findIndex(
          (e) => e.code === result.productType
        );
      },

      handleSave() {
        if (this.verifyParams()) {
          return;
        }
        if (this.inputObj.id) {
          this.updateProduct();
        } else {
          this.createProduct();
        }
      },

      getBody() {
        const data = JSON.parse(JSON.stringify(this.inputObj));
        data['supplierName'] = data.supplier?.customerName;
        data['supplierId'] = data.supplier?.id;
        data['userId'] = getDriverId();
        data.productType = data.productType?.code;
        delete data?.supplier;
        return data;
      },

      async updateProduct() {
        const data = this.getBody();
        const res = await updateProduct(data);

        if (res.code === 0) {
          uni.redirectTo({
            url: '/packageB/pages/product/index'
          });
          toast('修改成功');
        } else {
          toast('修改失败');
        }
      },

      async createProduct() {
        const data = this.getBody();
        delete data?.id;
        const res = await createProduct(data);
        if (res.code === 0) {
          uni.redirectTo({
            url: '/packageB/pages/product/index'
          });
          toast('新增成功');
          //成功后上报
          reportProduct(res.data);
        } else {
          toast('新增失败');
        }

      },
      verifyParams() {
        if (!this.inputObj.supplier) {
          toast('供应商不能为空');
          return true;
        }
        if (!this.inputObj.productType) {
          toast('产品类型不能为空');
          return true;
        }
        if (!this.inputObj.proName) {
          toast('产品名称不能为空');
          return true;
        }
        if (this.inputObj.proPrice < 0 || this.inputObj.proPrice > 10000000) {
          toast('产品价格的输入范围为0~9999999.99');
          return true;
        }
        if (!/^\d+(\.\d{1,2})?$/.test(this.inputObj.proPrice)) {
          toast('产品价格的输入范围为0~9999999.99');
          return true;
        }
        if (
          !this.inputObj.calorificValue ||
          !Number(this.inputObj.calorificValue) ||
          !(
            /^\d+(\.\d{1,2})?$/.test(this.inputObj.calorificValue) &&
            this.inputObj.calorificValue < 10000000
          )
        ) {
          toast('发热量的输入范围为0.01~9999999.99');
          return true;
        }
        if (this.validLessThan100(this.inputObj.ashContent)) {
          toast('灰分的输入范围为0.01~100.00');
          return true;
        }
        if (this.validLessThan100(this.inputObj.sulfurContent)) {
          toast('硫分的输入范围为0.01~100.00');
          return true;
        }
        if (this.validLessThan100(this.inputObj.hydration)) {
          toast('水分的输入范围为0.01~100.00');
          return true;
        }
        if (this.validLessThan100(this.inputObj.volatileMatter)) {
          toast('挥发分的输入范围为0.01~100.00');
          return true;
        }
        return false;
      },
      validLessThan100(value) {
        if (
          (value === '' || value === undefined || value === null) &&
          value !== 0
        ) {
          return false;
        }
        if (value == 0) {
          return true;
        }
        return !(/^\d+(\.\d{1,2})?$/.test(value) && value <= 100);
      },
      selectPicture() {
        let _ = this;
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size;
            if (curSize > 4 * 1024 * 1024) {
              toast('上传的图片不能超过4兆');
              return;
            }
            let quelityVal = 100;
            let initnum = 0.5 * 1024 * 1024;
            if (curSize > initnum) {
              quelityVal = Math.floor(100 / (curSize / initnum));
            }
            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                _.imagesPathRoad = [];
                _.uploadFilesId(resp.tempFilePath);
              }
            });
          },
          fail(e) {
            console.log('上传化验单失败', e);
          }
        });
      },
      uploadFilesId(filepath) {
        wx.showLoading({
          title: '正在上传中...'
        });
        let _ = this;
        uni.uploadFile({
          url: config.baseUrl + '/infra/file/upload/v2',
          filePath: filepath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            Authorization: 'Bearer ' + getAccessToken()
          },
          async success(res) {
            const data = JSON.parse(res?.data);
            wx.hideLoading();
            if (data.code === 0) {
              _.inputObj.assayReport = data.data;
              toast('上传成功');
            } else {
              if (data.code === 413) {
                toast('上传图片过大，请重新上传，不要选择原图');
              } else {
                toast('上传失败，状态码:', data.code);
              }
            }
          },
          fail() {
            wx.hideLoading();
            uni.showToast({
              title: '上传失败',
              icon: 'fail'
            });
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .phxx-item-detail {
    padding-bottom: 163rpx;

    .btns button {
      line-height: 40px;
    }
  }

  .upload-box {
    margin: 17.78rpx 0 0 17.78rpx;

    .img-box {
      position: relative;
      width: 266.67rpx !important;
      height: 160rpx !important;

      .cover-img {
        width: 100%;
        height: 100%;
        position: relative;
      }

      .camera-imgs {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 40rpx;
        margin: auto;
        width: 100rpx;
        height: 100rpx;
      }

      .img-text {
        position: absolute;
        bottom: 21.33rpx;
        left: 0;
        right: 0;
        text-align: center;
        line-height: 21.33rpx;
      }
    }
  }

  .placeholder {
    padding-left: 10rpx;
    color: #808080;
  }

  .phxx-item {
    width: 700rpx;
    padding: 10rpx 30rpx;
    box-sizing: border-box;
    margin: 20rpx auto 20rpx auto;
    border-radius: 20rpx;
    background: #fff;
    font-size: 26.66rpx;
    color: #000;

    .phxx-item-content {
      width: 644rpx;

      .bottom {
        padding: 10rpx 0 0 0;

        >.items {
          padding-bottom: 6rpx;
          display: flex;
          align-items: center;
          border-bottom: 1px solid #ccc;
          padding-top: 15px;
        }

        .btn {
          button {
            width: 100%;
            height: 40px !important;
            margin-top: 45px;
            line-height: 40px !important;
          }
        }

        .til {
          width: 150rpx;
          display: inline-block;
        }

        .val {
          margin-left: 30rpx;
          width: 75%;
          display: inline-block;
          border-radius: 5px;
          height: 30px;
        }
      }
    }
  }
</style>